using System;
using System.Web;

namespace Butterfly.Library.Utilities
{
	public class RefreshAction
	{
		#region Constants
		public const string LastRefreshTicketEntry = "__LASTREFRESHTICKET";
		public const string CurrentRefreshTicketEntry = "__CURRENTREFRESHTICKET";
		public const string PageRefreshEntry = "IsPageRefresh";
		#endregion

		// Manage to check if the F5 button has been pressed
		public static void Check(HttpContext ctx)
		{
			// Initialize the ticket slot
			EnsureRefreshTicket( ctx );

			// Read the last ticket served in the session (from Session)
			int lastTicket = GetLastRefreshTicket( ctx );

			// Read the ticket of the current request (from a hidden field)
			int thisTicket = GetCurrentRefreshTicket( ctx );

			// Compare tickets
			if( thisTicket > lastTicket || 
				(thisTicket==lastTicket && thisTicket==0) )
			{
				UpdateLastRefreshTicket( ctx, thisTicket );
				ctx.Items[PageRefreshEntry] = false;
			}
			else
			{
				ctx.Items[PageRefreshEntry] = true;
			}
		}// func


		#region Private Members
		// Ensure that the slot for the last ticket served isn't null
		private static void EnsureRefreshTicket(HttpContext ctx)
		{
			// Initialize the session slots for the page (Ticket) and the module (LastTicketServed)
			if( ctx.Session[LastRefreshTicketEntry] == null )
				ctx.Session[LastRefreshTicketEntry] = 0;
		}

		// Return the ticket of the last request in the session
		private static int GetLastRefreshTicket(HttpContext ctx)
		{
			// Extract and return the last ticket
			return Convert.ToInt32( ctx.Session[LastRefreshTicketEntry] );
		}

		// Return the ticket of the last request in the session
		private static int GetCurrentRefreshTicket(HttpContext ctx)
		{
			return Convert.ToInt32( ctx.Request[CurrentRefreshTicketEntry] );
		}

		// Return the ticket of the last request in the session
		private static void UpdateLastRefreshTicket(HttpContext ctx, int ticket)
		{
			ctx.Session[LastRefreshTicketEntry] = ticket;
		}

		#endregion
	
	}// class
}
